<template>
  <view class="page-container">
    <view class="recent-box">
      <view class="recent-header">
        <text class="recent-title">最新订单</text>
        <view class="more-btn" size="mini" @click="viewMoreOrders" v-if="storeId">更多</view>
      </view>
      <view class="order-list" v-if="orders.length > 0">
        <view class="order-item" v-for="order in displayedOrders" :key="order.order_id">
          <view class="customer-info">
            <text class="name">{{ order.customer ? order.customer.name : '1' }}</text>
            <view class="amount-info">
              <text class="actual-amount">实付: ¥{{ order.actual_amount }}</text>
              <text class="amount strike">¥{{ order.total_amount }}
                <text class="card-package" v-if="order.card_package">
                  卡包: {{ order.card_package.name }} ({{ cardTypeMap[order.card_package.card_type] ||
                    order.card_package.card_type }})
                </text></text>

            </view>
            <text class="phone">{{ order.customer ? order.customer.phone : '2' }}</text>

          </view>
          <view class="order-time">
            {{ formatTime(order.created_at) }}
          </view>
        </view>
      </view>

      <view class="empty" v-else>
        <text>暂无最近30分钟的订单</text>
      </view>
    </view>
  </view>
</template>

<script>
import order from '@/utils/order.js';

export default {
  props: {
    storeId: {
      type: String,
      required: false,  // 添加required配置
      default: ''       // 确保有默认值
    },
    showCount: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      orders: [],
      cardTypeMap: {
        'default': '默认卡',
        'comprehensive': '综合卡',
        'per_use': '次卡'
      }
    };
  },
  watch: {
    // 监听storeId变化，如果父组件传入的storeId变化，重新加载数据
    storeId(newVal) {
      if (newVal) {
        this.fetchRecentOrders();
      }
    }
  },
  created() {
    console.log('RecentOrders.vue created', this.storeId);
    this.fetchRecentOrders();
  },
  // 添加onShow生命周期钩子
  onShow() {
    this.fetchRecentOrders();
  },
  methods: {
    async fetchRecentOrders() {
      try {
        const now = new Date();
        const endTime = this.formatDateTime(now);
        const thirtyMinutesAgo = new Date(now.getTime() - 30 * 60 * 1000);
        const startTime = this.formatDateTime(thirtyMinutesAgo);

        const params = {
          start_time: startTime,
          end_time: endTime
        };

        if (this.storeId) {
          params.store_id = this.storeId;
        }

        const response = await order.getList(params);
        this.orders = response.list;
      } catch (error) {
        console.error('获取最近订单失败:', error);
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        });
      }
    },
    formatTime(timeString) {
      const time = new Date(timeString);
      const hours = time.getHours().toString().padStart(2, '0');
      const minutes = time.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    viewMoreOrders() {
      uni.navigateTo({
        url: `/pages/order/index?store_id=${this.storeId}`
      });
    },
  },
  computed: {
    displayedOrders() {
      return this.orders.slice(0, this.showCount);
    }
  }
};
</script>

<style lang="scss">
@import '@/uni.scss';

.page-container {
  padding: 20rpx;
}

.order-list {
  margin-top: 30rpx;
}

.order-item {
  background: #fff;
  border-radius: $uni-border-radius-lg;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.customer-info {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
}

.name {
  font-size: 32rpx;
  font-weight: bold;
  color: $uni-main-color;
  margin-bottom: 10rpx;
}

.amount-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.actual-amount {
  font-size: 28rpx;
  color: $uni-primary;
  font-weight: bold;
}

.amount {
  font-size: 26rpx;
  color: $uni-text-color-grey;
}

.phone {
  font-size: 26rpx;
  color: $uni-secondary-color;
}

.order-time {
  align-self: flex-end;
  font-size: 26rpx;
  color: $uni-secondary-color;
}

.empty {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
}

.more-btn {
  margin-left: 10rpx;
  color: #09BB07;
  border: none;
  border-radius: $uni-border-radius-lg;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  padding: 10rpx 20rpx;
}

.card-package {
  font-size: 24rpx;
  color: #666;
  margin-top: 5rpx;
}
.recent-box {
    display: flex;
    justify-content: center;
    margin-bottom: 20rpx;
    border-radius: $uni-border-radius-lg;
    padding: 15rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    background: #fff;
    flex-direction: column;
}
.recent-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;

}
</style>